﻿namespace SuperMarieApi.App.Controllers.Framework.DataAccess
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Reflection;

    public static class EntityBuilder
    {
        private static Dictionary<Type, List<KeyValuePair<PropertyInfo, DataMapping>>> _propCache;

        static EntityBuilder()
        {
            _propCache = new Dictionary<Type, List<KeyValuePair<PropertyInfo, DataMapping>>>();
        }

        private static List<KeyValuePair<PropertyInfo, DataMapping>> GetEntityPropertyInfoList(Type type)
        {
            if (type == null)
            {
                return null;
            }

            //如果缓存中存在就直接返回
            if (_propCache.ContainsKey(type))
            {
                return _propCache[type];
            }

            //缓存中不存在就通过反射获取，并缓存
            var result = new List<KeyValuePair<PropertyInfo, DataMapping>>();
            var propInfoArr = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            Type columnMappingType = typeof(DataMapping);
            Array.ForEach(propInfoArr, (prop) =>
            {
                var colMappingArr = prop.GetCustomAttributes(columnMappingType, true);
                if (colMappingArr.Length == 1)
                {
                    var colMap = colMappingArr[0] as DataMapping;
                    colMap.ColumnName = (colMap.ColumnName ?? string.Empty).Trim();
                    if (colMap.ColumnName.Length > 0)
                    {
                        var kv = new KeyValuePair<PropertyInfo, DataMapping>(prop, colMap);
                        result.Add(kv);
                    }
                }
            });
            _propCache[type] = result;

            return result;
        }

        private static T BuildEntityInternal<T>(DataTable dt, int rowIndex) where T : new()
        {
            var dr = dt.Rows[rowIndex];
            var propList = GetEntityPropertyInfoList(typeof(T));
            if (propList != null)
            {
                var entity = new T();
                Type vType = null;
                foreach (var propColMap in propList)
                {
                    if (dt.Columns.Contains(propColMap.Value.ColumnName))
                    {
                        var value = dr[propColMap.Value.ColumnName];
                        if (value != DBNull.Value)
                        {
                            vType = value.GetType();
                            if (vType == typeof(string))
                            {
                                value = value.ToString().Trim();
                            }
                            try //todo： 临时处理MySql 数字类型常量为Int64问题
                            {
                                if (vType == typeof(Int64) && propColMap.Value.ColumnType == DbType.Int32)//常量问题
                                {
                                    if (Convert.ToInt64(value) <= Convert.ToInt64(Int32.MaxValue)
                                        && Convert.ToInt64(value) >= Convert.ToInt64(Int32.MinValue))
                                    {
                                        propColMap.Key.SetValue(entity, Convert.ToInt32(value), null);
                                    }
                                }
                                else if (vType == typeof(System.Single) && propColMap.Value.ColumnType == DbType.Double)//float问题
                                {
                                    propColMap.Key.SetValue(entity, Convert.ToDouble(value), null);
                                }
                                else
                                {
                                    propColMap.Key.SetValue(entity, value, null);
                                }

                            }
                            catch (Exception)
                            {
                                propColMap.Key.SetValue(entity, value, null);
                            }
                        }
                    }
                }
                return entity;
            }
            return default(T);
        }

        public static T BuildEntity<T>(DbDataReader dataReader) where T : new()
        {
            if (dataReader != null && dataReader.IsClosed == false)
            {
                DataTable dt = new DataTable();
                dt.Load(dataReader);
                dataReader.Close();
                if (dt.Rows.Count > 0)
                {
                    return BuildEntityInternal<T>(dt, 0);
                }
            }

            return default(T);
        }

        public static List<T> BuildEntityList<T>(DbDataReader dataReader) where T : new()
        {
            List<T> result = new List<T>();

            if (dataReader != null && dataReader.IsClosed == false)
            {
                DataTable dt = new DataTable();
                dt.Load(dataReader);
                dataReader.Close();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    result.Add(BuildEntityInternal<T>(dt, i));
                }
            }

            return result;
        }

        public static T BuildEntity<T>(DataRow dr) where T : new()
        {
            if (dr != null)
            {
                DataTable dt = new DataTable();
                dt.Rows.Add(dr);
                if (dt.Rows.Count > 0)
                {
                    return BuildEntityInternal<T>(dt, 0);
                }
            }
            return default(T);
        }

        public static List<T> BuildEntityList<T>(DataTable dt) where T : new()
        {
            List<T> result = new List<T>();
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    result.Add(BuildEntityInternal<T>(dt, i));
                }
            }
            return result;
        }
    }
}
